//
//  JXHNetWorkTools.swift
//  JXHSinaWeiBo
//
//  Created by juxiaohui on 16/10/19.
//  Copyright © 2016年 juxiaohui. All rights reserved.
//

import UIKit

import AFNetworking

enum RequestType : NSInteger {
    case GET  = 0
    case POST = 1
}
class JXHNetWorkTools: AFHTTPSessionManager {
    
    
    //let 保证线程安全
    static let shareInstance : JXHNetWorkTools = {
        
        let tools = JXHNetWorkTools()
        
        tools.responseSerializer.acceptableContentTypes?.insert("text/html")
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tools
    }()
}


// MARK: - 封装请求方法

extension JXHNetWorkTools {
    
    
    
    //1.定义成功回调的闭包
    //
    //    var successHandle = { (task : URLSessionDataTask, result : Any?) in
    //
    //        finished(result, nil)
    //    }
    
    
    //2.定义失败回调的闭包
    
    func request(methodType : RequestType, URLString: String,parameters: [String : Any],finished : @escaping (_ response : Any?, _ error : Error?)->()) {
        
        if methodType == .GET {
            
            get(URLString, parameters: parameters, progress: { (progress : Progress) in
                
                }, success: { (task : URLSessionDataTask, result : Any?) in
                    
                    finished(result, nil)
                }, failure: { (task : URLSessionDataTask?, error : Error) in
                    finished(nil, error)
            })
            
        }else{
            
            post(URLString, parameters: parameters, progress: { (progress : Progress) in
                
                }, success: { (task : URLSessionDataTask, result : Any?) in
                    finished(result, nil)
                }, failure: { (task : URLSessionDataTask?, error : Error) in
                    finished(nil, error)
            })
        }
    }
}


// MARK: - 请求AccessToken

extension JXHNetWorkTools {

    func loadAccessToken(code : String,finished :@escaping (_ response : Any?, _ error : Error?)->()) {
       
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        let parameters = ["client_id" : app_key,"client_secret" : app_Secret,"grant_type" : "authorization_code","code" : code,"redirect_uri" : redirect_uri]
        
        request(methodType: .POST, URLString: urlString, parameters: parameters) { (response : Any?, error : Error?) in
            
            finished(response, error)
        }
    }
}


// MARK: - 请求用户信息

extension JXHNetWorkTools {


    func loadUserInfo(access_token : String,uid : String,finished :@escaping (_ response : [String :Any]?, _ error : Error?)->()) {
        
        let urlString = "https://api.weibo.com/2/users/show.json"
        
        let parameters = ["access_token" : access_token,"uid" : uid]
        
        request(methodType: .GET, URLString: urlString, parameters: parameters) { (response : Any?, error : Error?) in

            finished(response as? [String :Any], error)
        }
    }
}

// MARK: - 请求首页数据
extension JXHNetWorkTools {

    func loadStatus(since_id : Int, max_id : Int, finished :@escaping (_ response : [[String :Any]]?, _ error : Error?)->()) {
        
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        
        let parameters = ["access_token" : (JXHUserAcccountTool.shareInstance.accont?.access_token)!,"since_id" : "\(since_id)","max_id" : "\(max_id)" ]
        
        request(methodType: .GET, URLString: urlString, parameters: parameters) { (response : Any?, error : Error?) in
            
            guard let response = response as? [String :Any] else{
                finished(nil, error)
                return
            }
            
            /// 回调出去微博数组
            finished(response["statuses"] as? [[String :Any]] ,error)
        }
    }
}

// MARK: -  发送微博
extension JXHNetWorkTools {

    func sentStatus(text : String,isSuccess : @escaping ( _ isSuccess : Bool) -> ()) {
        
        let urlString = "https://api.weibo.com/2/statuses/update.json"
        
        let parameters = ["access_token" : (JXHUserAcccountTool.shareInstance.accont?.access_token)!,"status" : text ]
        request(methodType: .POST, URLString: urlString, parameters: parameters) { (result, error) in
            
            if error != nil {
    
                isSuccess(false)
            }else{
                isSuccess(true)

            }
        }
    }
}

// MARK: -  发送带图片的微博
extension JXHNetWorkTools {
    
    func sentStatus(text : String,image : UIImage, isSuccess : @escaping ( _ isSuccess : Bool) -> ()) {
        
        let urlString = "https://api.weibo.com/2/statuses/upload.json"
        
        let parameters = ["access_token" : (JXHUserAcccountTool.shareInstance.accont?.access_token)!,"status" : text ]
        
        //发送请求
        post(urlString, parameters: parameters, constructingBodyWith: { (formData) in
            
            if let data = UIImageJPEGRepresentation(image, 0.5){
                formData.appendPart(withFileData: data, name: "pic", fileName: "123.png", mimeType: "image/png")
            }
            
            }, progress: { (progress) in
                
            }, success: { (_, _) in
                
                isSuccess(true)
                
            }) { (_, error) in
                isSuccess(false)
                print(error)
        }
    }
}


